<template>
  <view class="rf-search-bar bg-primary">
    <view class="header" :style="{
      width: clientInfo.width + 'px',
      marginTop: clientInfo.inputTop + 'px'
    }">
      <!-- 城市 -->
      <view @click="openSelector" class="city-box">
        {{ address?.cityShortName || '定位中' }}
        <u-icon class="icon" :class="{ 'rotate-icon': selectorShow }" name="arrow-down-fill" size="24"
          color="#fff"></u-icon>
      </view>
      <!-- 搜索框 -->
      <view class="input-box" @tap="toSearch">
        <input class="input" disabled />
        <view class="wrapper">
          <text class="iconfont hy-icon-search"></text>
          <text class="keyword">{{ placeholder }}</text>
        </view>
      </view>
      <!-- 扫一扫 -->
      <view class="icon-box">
        <text class="iconfont" @tap.stop="link" :class="[icon]"></text>
      </view>
    </view>
    <u-select v-model="selectorShow" mode="mutil-column-auto" :list="cityList" :default-value="selectDefault"
      @confirm="selectorConfirm"></u-select>
  </view>
  <view class="placeholder-box" :style="{
    height: clientInfo.height + 'px'
  }"></view>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { getQueryObject } from '@/utils/common'
import { useUserStore } from '@/store'
import { getLocation } from '@/utils'
import { baseApi } from '@/api'
import { jsSdkConfig, scanQRCode } from '@/common/wechat-share' // 引入 scanQRCode

const userStore = useUserStore()
const { hasLogin } = storeToRefs(userStore)
const emit = defineEmits(['onSearch'])
const props = withDefaults(
  defineProps<{
    placeholder?: string
    icon?: string
    topDistance?: number
  }>(),
  {
    placeholder: '热门搜索',
    icon: 'hy-icon-scan',
    topDistance: 0
  }
)
const clientInfo = reactive({
  width: 0,
  height: 0,
  inputTop: 0
})

const selectorShow = ref(false)
function selectorConfirm(e: any) {
  console.log(e)
}
interface Address {
  cityShortName?: string
  cityName?: string
  districtName?: string
  provinceName?: string
  provinceId?: number
  cityId?: number
  districtId?: number
}
const address = ref<Address>()
async function getCurrentCity() {
  const location = await getLocation(true)
  const { data } = await baseApi.reverseGeocoding(location)
  address.value = addressFormat(data)
  uni.setStorageSync('currentAddress', address.value)
  console.log(address.value)
}
function addressFormat(address: Address): Address {
  if (typeof address === 'undefined' || address === null || JSON.stringify(address) === '{}') {
    return {}
  }
  if (typeof address.cityName !== 'undefined' && address.cityName !== null) {
    address.cityShortName = address.cityName.split('市')[0]
  }
  return address
}
getCurrentCity()


const cityList = ref<object[]>([])
interface Area {
  id: string
  name: string
  parentId: string
  deep: number
}
function partTree(tableData: Area[], keys = ["label", "value"]): object[] {
  let p = [];
  let c = [];
  let a = [];
  for (var i = 0; i < tableData.length; i++) {
    tableData[i][keys[0]] = tableData[i].name;
    tableData[i][keys[1]] = tableData[i].id;
    const deep = tableData[i].deep
    deep == 1 && p.push(tableData[i]);
    deep == 2 && c.push(tableData[i]);
    deep == 3 && a.push(tableData[i]);
  }
  for (var i = 0; i < a.length; i++) {
    for (var j = 0; j < c.length; j++) {
      !c[j].children && (c[j].children = []);
      if (a[i].parentId == c[j].id) {
        c[j].children.push(a[i]);
      }
    }
  }
  for (var i = 0; i < c.length; i++) {
    for (var j = 0; j < p.length; j++) {
      !p[j].children && (p[j].children = []);
      if (c[i].parentId == p[j].id) {
        p[j].children.push(c[i]);
      }
    }
  }
  return p;
}
function getRegionDate() {
  uni.request({
    url: 'https://image.blacksilverscore.com/App/bbd3f87e-7e56-4b1d-8d53-97c3313391f4.json',
    data: {},
    header: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'X-Requested-With': 'XMLHttpRequest'
    },
    method: 'GET',
    sslVerify: true,
    success: ({ data, statusCode, header }) => {
      cityList.value = partTree(data as Area[])
      console.log(cityList.value)
    },
    fail: (error) => { }
  })
}
getRegionDate()
const selectDefault = reactive<number[]>([])
function openSelector() {
  selectorShow.value = !selectorShow.value
  if (selectorShow.value) {
    if (typeof address.value !== 'undefined' && address.value !== null && JSON.stringify(address.value) !== '{}') {
      const { provinceId, cityId, districtId } = address.value
      const pIdx = cityList.value.findIndex((item) => item.id === provinceId)
      const cIdx = cityList.value[pIdx]?.children?.findIndex((item: { id: number | undefined }) => item.id === cityId)
      const dIdx = cityList.value[pIdx]?.children[cIdx]?.children?.findIndex((item: { id: number | undefined }) => item.id === districtId)
      selectDefault.splice(0, selectDefault.length, pIdx, cIdx, dIdx)
    } else {
      selectDefault.splice(0, selectDefault.length, 0, 0, 0)
    }
  }
}
// #ifdef MP-WEIXIN
const obj = wx.getMenuButtonBoundingClientRect()
// #endif
// #ifdef H5
const obj = {
  top: 15,
  height: 40
}
// #endif
uni.getSystemInfo({
  success: (res) => {
    clientInfo.width = obj.left || res.windowWidth
    clientInfo.height = obj.top
      ? obj.top + obj.height + props.topDistance
      : res.statusBarHeight
    clientInfo.inputTop = obj.top
      ? obj.top + (obj.height - 30) / 2
      : res.statusBarHeight + 7
  }
})

// 扫一扫
const link = () => {
  console.log('扫一扫', getLocation())
  if (!hasLogin) {
    uni.showModal({
      title: '提示',
      content: '登录后可使用扫码',
      showCancel: true,
      success: ({ confirm, cancel }) => {
        if (confirm) {
          uni.navigateTo({
            url: '/pages/login/index'
          })
        }
      }
    })
    return
  }
  // #ifdef H5
  scanQRCode() // 调用 scanQRCode 函数
  // #endif
  // #ifdef MP-WEIXIN
  uni.scanCode({
    success(res) {
      const { result } = res
      if (result) {
        const params = getQueryObject(result)
        const { redirect_url, shopId } = params
        if (redirect_url) {
          uni.navigateTo({
            url: `${redirect_url}?shopId=${shopId}`
          })
        }
      }
    },
    fail(_res) { console.error('小程序扫码失败:', _res) }
  })
  // #endif
}
const toSearch = () => {
  emit('onSearch')
}
</script>

<style lang="scss" scoped>
.rf-search-bar {
  padding-bottom: 36rpx;
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  z-index: 10;

  .header {
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 12;

    .city-box {
      color: #fff;
      padding-left: 10rpx;

      .icon {
        transition: transform 0.3s ease;

        &.rotate-icon {
          transform: rotate(180deg);
        }
      }

    }

    .icon-box {
      margin: 0 $uni-spacing-row-sm 0 0;
      color: $uni-text-color-inverse;

      .iconfont {
        font-weight: 400;
        font-size: 50rpx;
      }

      .logo {
        width: 45rpx;
        height: 45rpx;
        border-radius: 8rpx;
        margin-left: 10rpx;
      }
    }

    .input-box {
      flex: 1;
      height: 60rpx;
      line-height: 60rpx;
      background-color: $uni-bg-color-white;
      border-radius: 30rpx;
      position: relative;
      display: flex;
      align-items: center;
      margin: 0 $uni-spacing-row-sm;

      .wrapper {
        display: flex;
        align-items: center;
        position: absolute;
        top: 50%;
        left: 50%;
        font-size: $uni-font-size-sm + 2rpx;
        color: $uni-text-color-light;
        transform: translate(-50%, -50%);

        .iconfont {
          font-size: 34rpx;
          margin-right: $uni-spacing-row-sm;
        }
      }

      .input {
        width: 100%;
        padding-left: 28rpx;
        height: 28rpx;
        color: #888;
        font-size: 28rpx;
      }
    }
  }
}

.bg {
  &-primary {
    background-color: $bg-primary;
  }
}

.placeholder-box {
  width: 100%;
  padding-bottom: 40rpx;
  box-sizing: content-box;
}
</style>
